package com.xxl.job.admin.util;

import com.google.gson.JsonObject;
import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.model.CrmInterfaceUrlVO;
import groovy.util.logging.Slf4j;
import org.apache.ibatis.reflection.ExceptionUtil;
import org.apache.tomcat.util.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * Title:
 *
 * @author junyu 2023-04-12 15:01
 */
public class DDTalkUtil {

    private static Logger logger = LoggerFactory.getLogger(DDTalkUtil.class);

    private static RestTemplate restTemplate = new RestTemplate();

    public static void toTalk(String jobtitle,String text,long jobid){
        try {
            CrmInterfaceUrlVO crmInterfaceUrlVO = XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().getEnv("***");
            logger.info("获取对象："+crmInterfaceUrlVO.toString());
            //不提醒
            if ("N".equals(crmInterfaceUrlVO.getUseYn())) {
                return;
            }
            String finalUrl = "https://oapi.dingtalk.com/robot/send?access_token=***";
            JsonObject json = new JsonObject();
            json.addProperty("msgtype","link");
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/json;charset=UTF-8");
            JsonObject link = new JsonObject();
            link.addProperty("text",text);
            link.addProperty("title",crmInterfaceUrlVO.getName()+jobtitle);
            link.addProperty("messageUrl",crmInterfaceUrlVO.getUrl()+jobid);
            json.add("link",link);
            HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
            logger.info(restTemplate.exchange(finalUrl, HttpMethod.POST, formEntity, String.class, (Object) null).getBody());
        }catch (Exception e){
            logger.error("钉钉报警错误：{}",e.getMessage());
        }
    }
}